﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FineUI;
using SysManage.BLL;
using ZHDJ.Core;
using ZHDJ.Core.Log;
using ZHDJ.Core.Office;
using ZHDJ.Core.Util;
using ZHDJ.Data;
using ZHDJ.Data.Models.Questionnaire;
using ZHDJ.WebPage;

namespace SysManage.Module.Questionnaire
{
    public partial class PartyQuestionnaireSubjectList : PageBase
    {
        public string QuestionnaireId
        {
            get
            {
                var m = GetQueryIntValue("id");
                if (m == "")
                {
                    return BranchID;
                }
                return m;
            }
        }
        #region ViewPower

        /// <summary>
        /// 本页面的浏览权限，空字符串表示本页面不受权限控制
        /// </summary>
        public override string ViewPower
        {
            get
            {
                return "PartyQuestionnaireView";
            }
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
                LoadData();
            }
        }

        #region 数据加载
        private void BindData()
        {
            // 权限检查
            CheckPowerWithButton("PartyQuestionnaireAdd", btnAdd);

            btnAdd.OnClientClick = Dialog.GetShowReference("PartyQuestionnaireSubjectEdit.aspx?QuestionnaireId=" + QuestionnaireId, "新增");

            // 每页记录数
            Grid1.PageSize = ConfigHelper.PageSize;
            ddlGridPageSize.SelectedValue = ConfigHelper.PageSize.ToString();
        }
        private void LoadData()
        {
            var ds = PartyQuestionnaireSubject.GetGridData(Grid1.PageIndex, Grid1.PageSize, QuestionnaireId,
                txtTitle.Text);

            Grid1.RecordCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
            Grid1.DataSource = ds.Tables[0];
            Grid1.DataBind();
        }

        protected void Grid1_PreDataBound(object sender, EventArgs e)
        {
            // 数据绑定之前，进行权限检查
            CheckPowerWithWindowField("PartyQuestionnaireEdit", Grid1, "editField");
            CheckPowerWithLinkButtonField("PartyQuestionnaireDelete", Grid1, "deleteField");
        }

        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            Grid1.SortDirection = e.SortDirection;
            Grid1.SortField = e.SortField;
            LoadData();
        }

        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            LoadData();
        }

        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            string PartyQuestionnaireSubjectId = GetSelectedDataKeyID(Grid1);

            if (e.CommandName == "Delete")
            {
                // 在操作之前进行权限检查
                if (!CheckPower("PartyQuestionnaireDelete"))
                {
                    CheckPowerFailWithAlert();
                    return;
                }

                var del = DB.PartyQuestionnaireSubjects.FirstOrDefault(t => t.ID == PartyQuestionnaireSubjectId);

                DB.PartyQuestionnaireSubjects.Remove(del);
                if (DB.SaveChanges() > 0)
                {

                }
                LoadData();
            }
        }

        public static string GetBranchName(string branchId)
        {
            return ControlBusiness.GetBranchPickerText(branchId);
        }

        #endregion

        #region 按钮事件
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            LoadData();
        }
        protected void btnDeleteSelected_Click(object sender, EventArgs e)
        {
            // 在操作之前进行权限检查
            if (!CheckPower("PartyQuestionnaireDelete"))
            {
                CheckPowerFailWithAlert();
                return;
            }

            // 从每个选中的行中获取ID（在Grid1中定义的DataKeyNames）
            List<string> ids = GetSelectedDataKeyIDs(Grid1);
            List<string> listLoginid = new List<string>();
            // 执行数据库操作
            DB.PartyQuestionnaireSubjects.Where(u => ids.Contains(u.ID)).ToList().ForEach(
                u =>
                {

                    DB.PartyQuestionnaireSubjects.Remove(u);

                });
            if (DB.SaveChanges() > 0)
            {

            }

            // 重新绑定表格
            LoadData();
        }
        #endregion

        protected void Dialog_Close(object sender, EventArgs e)
        {
            LoadData();
        }

        protected void ddlGridPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageSize = Convert.ToInt32(ddlGridPageSize.SelectedValue);
            LoadData();
        }

        #region 导入

        protected void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                NpoiHelper npoiHelper = new NpoiHelper();
                //1.获取从EXCEEL导入进来的数据
                DataSet ds = npoiHelper.ReadToDataSet(this.fuFile, "Sheet1", 0, 1, 19);
                if (ds == null)
                {
                    return;
                }
                if (Convert.ToString(ds.Tables[0].Columns[0].ColumnName).Trim() != "题目0")
                {
                    Alert.Show("导入文档格式不正确，请下载模板！");
                    
                    return;
                }
                string strSQL = "";
                ds.Tables[0].Columns.Add("ID");
                //bool isFirst = true;
                int index = DB.PartyQuestionnaireSubjects.Count(a => a.QuestionnaireID == QuestionnaireId);
                foreach (DataRow item in ds.Tables[0].Rows)
                {
                    if (Convert.ToString(item[0]).Trim() == "")
                    {
                        continue;
                    }
                    index += 1;
                    string sID = StringHelper.NewID;
                    string sCreatePeople = CurrentUser.LoginID;
                    item["ID"] = sID;
                    var category = item[1].ToString().Trim().Equals("是") ? "1" : "2";
                    //题目
                    strSQL += string.Format(@"  INSERT INTO tblPartyQuestionnaireSubject
                        (ID,QuestionnaireID,Category,Title,CreateBy,CreateTime,ModifyBy,ModifyTime,OrderNo,Enabled)
                        VALUES('{0}','{1}','{2}','{3}','{4}',NOW(),'{4}',NOW(),{5},1);",
                        sID, this.QuestionnaireId, category, item[0], sCreatePeople, index);
                    int j = 1;
                    for (int i = 2; i < ds.Tables[0].Columns.Count; i = i + 2)
                    {
                        if (!string.IsNullOrEmpty(item[i].ToString()))
                        {
                            string aStr = "0";
                            if (!string.IsNullOrEmpty(item[i + 1].ToString()))
                            {
                                if (item[i + 1].ToString().Trim().Equals("是"))
                                {
                                    aStr = "1";
                                }
                            }
                            //选项
                            strSQL += string.Format(@"INSERT INTO tblpartyquestionnaireoption
                        (ID,SubjectID,Title,ChoicePercent,ChoiceCount,OrderNo,CreateBy,CreateTime,ModifyBy,ModifyTime,IsTk)
                        VALUES('{0}','{1}','{2}',0,0,{3},'{4}',NOW(),'{4}',NOW(),{5});",
                                StringHelper.NewID, sID, Convert.ToString(item[i]).Trim(), j, sCreatePeople, aStr);
                            j++;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                if (MySqlHelper.ExecuteNonQuery(strSQL) > 0)
                {
                    Alert.Show("数据导入成功!");
                }
                this.LoadData();

            }
            catch (Exception ex)
            {

                Log4netHelper.WriteLog(ex);
                Alert.Show("导入文档格式不正确，请下载模板!"+ex.Message);
                //Page.ClientScript.RegisterStartupScript(Page.GetType(), "", "alert('导入文档格式不正确，请下载模板！');", true);
                return;
            }
        }
        #endregion
    }
}